/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package br.ufrgs.inf.prav.interop.util;

import br.ufrgs.inf.prav.interop.detectors.MobileDeviceDetector;
import br.ufrgs.inf.prav.interop.detectors.TVDeviceDetector;
import br.ufrgs.inf.prav.interop.resource.ClientType;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Fernando Arena Varella
 * @version 1.0
 */
public class HTTPClientIdentifier {

    public HTTPClientIdentifier(){

    }

    public static ClientType getClientType(){
        return getClientType(FacesContext.getCurrentInstance());
    }

    public static ClientType getClientType(FacesContext context){
        HttpSession session = (HttpSession)context.getExternalContext().getSession(false);
        try {
            ClientType clientType = (ClientType)session.getAttribute("client-type");
            if (clientType != null)
                return clientType;
            else {
                clientType = identifyClientTypeFromRequest(context);
                session.setAttribute("client-type", clientType);
                return clientType;
            }

        } catch (Exception e) {
            ClientType clientType = identifyClientTypeFromRequest(context);
            session.setAttribute("client-type", clientType);
            return clientType;
        }

    }

    /**
     * Parses the request headers to discover the client's type
     * @param context   the current Faces Context
     * @return  the CientType of the client
     */
     public static ClientType identifyClientTypeFromRequest(FacesContext context){
//        System.out.println("User-Agent: " + request.getHeader("user-agent"));
        try {

            HttpServletRequest request = (HttpServletRequest)
                    context.getExternalContext().getRequest();
            if (TVDeviceDetector.isTV(request))
                return ClientType.DIGITALTV;
            if (MobileDeviceDetector.isMobile(request))
                return ClientType.MOBILE;
            return ClientType.WEB;

        } catch (Exception e) {
            System.out.println("Error on device detecors: " + e.getMessage());
            return ClientType.WEB;
        }
//        Enumeration e;
//        for (e = request.getHeaderNames(); e.hasMoreElements();) {
//            String name = (String) e.nextElement();
//            System.out.println("Name: " + name + "   -   Value: " + request.getHeader(name));
//        }

    }

}
